package cn.weakup.juc;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * @author lixj
 * @date 2022/5/18
 * @desc
 */
public class ConcurrentHashMapTest {
    public static void main(String[] args) throws Exception{
        //concurrentHashMapVSHashMap();
        concurrentHashMapConstructor();
    }

    /**
     * 构造方法对初始化容量的影响
     */
    public static void concurrentHashMapConstructor() throws Exception {
        Field tableNodeArr = ConcurrentHashMap.class.getDeclaredField("table");
        tableNodeArr.setAccessible(true);

        ConcurrentHashMap map = new ConcurrentHashMap();
        Object o = tableNodeArr.get(map);
        System.out.println(o);

        ConcurrentHashMap map2 = new ConcurrentHashMap(3);
        map2.get("a");
        map2.remove("a","111");
    }

    /**
     * 比较HashMap为什么不是线程安全的
     * @throws InterruptedException
     */
    public static void concurrentHashMapVSHashMap() throws InterruptedException {
        ConcurrentHashMap jucmap = new ConcurrentHashMap(10001,1 );
        HashMap map = new HashMap(10001,1 );
        CountDownLatch count = new CountDownLatch(10000);
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            new Thread(()-> {
                map.put(finalI, finalI);
                jucmap.put(finalI, finalI);
                count.countDown();
            }).start();
        }

        count.await();
        System.out.println(map.size());
        System.out.println(jucmap.size());
    }
}
